package com.atguigu.spzx.manager.service.Impl;

import com.atguigu.spyx.model.common.com.atguigu.spyx.model.entity.sys.SysMenu;
import com.atguigu.spzx.manager.mapper.SysMenuMapper;
import com.atguigu.spzx.manager.mapper.SysRoleMenuMapper;
import com.atguigu.spzx.manager.service.SysRoleMenuService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author LT
 * @create 2023-11-07-11:17
 */
@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService {

    @Resource
    SysRoleMenuMapper sysRoleMenuMapper;

    @Resource
    SysMenuMapper sysMenuMapper;

    @Override
    public Map<String, Object> findMenusByRoleId(Long roleId) {
        //查询所有的菜单 并且挑选可用菜单列表
        List<SysMenu> menus = sysMenuMapper.findAll()
                .stream().filter(sysMenu ->
                       sysMenu.getStatus().intValue()==1 )
                .collect(Collectors.toList());
        //将菜单组装成父子菜单集合
        List<SysMenu> parents = menus.stream().filter(sysMenu ->
                sysMenu.getParentId().longValue() ==0l)
                .collect(Collectors.toList());
        buildMenuTree(menus,parents);
        //查询角色的已分配的菜单id集合
        List<Long> menuIds = sysRoleMenuMapper.findMenusByRoleId(roleId);
        //组装数据返回
        Map<String,Object> map = new HashMap<>();
        //返回组装好的菜单列表
        map.put("menus",parents);
        map.put("menuIds",menuIds);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignMenus2Role(Long roleId, List<Long> menuIds) {
        sysRoleMenuMapper.deleteByroleId(roleId);

        sysRoleMenuMapper.assignMenus2Role(roleId,menuIds);
    }

    private void buildMenuTree(List<SysMenu> all, List<SysMenu> parents) {
        if (CollectionUtils.isEmpty(parents)){
            return;
        }
        parents.forEach(parent->{
            List<SysMenu> children = all.stream().filter(sysMenu -> sysMenu.getParentId().longValue()==
                    parent.getId().longValue()).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(children)){
                parent.setChildren(children);
            }
            buildMenuTree(all,children);
        });
    }
}
